package com.woniu.cms.psm.core.controller;


import com.aliyun.oss.OSSClient;
import com.woniu.cms.psm.core.entity.Attachment;
import com.woniu.cms.psm.core.service.IAttachmentService;
import com.woniu.common.api.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lilili
 * @since 2022-09-24
 */
@Slf4j
@RestController
@RequestMapping("/attachment")
@Api(tags = "附件控制器")
public class AttachmentController {
    @Resource
    private IAttachmentService attachmentService;


    //注入aliyun的开发工具
    @Resource
    private OSSClient ossClient;
    //指定桶的名字
    private static final String BUCKETNAME = "xlydyjy";
    //指定文件url的前缀
    private static final String BASE_URL = "https://xlydyjy.oss-cn-chengdu.aliyuncs.com";

    @ApiOperation("文件上传")
    @PostMapping("/auth/upload")
    public Result<Object> upload(HttpServletRequest request, MultipartFile uploadFile, @RequestParam String remark) throws IOException {
        //上传时的文件名
        String originalFilename = uploadFile.getOriginalFilename();
        log.info(originalFilename);

        //得到不重复文件名字
        String fileName = UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info(fileName);

        //得到文件流对象
        InputStream inputStream = uploadFile.getInputStream();

        //设置上传参数
        ossClient.putObject(BUCKETNAME, fileName, inputStream);

        //设置过期时间(因为现在的服务器是免费的就需要设置过期时间，以后花钱的服务器不需要)
        Date date = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 30);

        //上传文件 得到URL对象
        URL url = ossClient.generatePresignedUrl(BUCKETNAME, fileName, date);
        log.info(url.getPath());

        long size = uploadFile.getSize();
        log.info(String.valueOf(size));

        //完整路径
        String fullURl = BASE_URL + url.getPath();


        String userName = request.getHeader("userName");
        Attachment attachment = new Attachment();
        attachment.setId(null).setFileName(originalFilename)
                .setSaveName(fileName).setUrl(fullURl).setSize(new BigDecimal(size/1024/1024))
                .setPerson(userName).setRemark(remark);
        boolean save = attachmentService.save(attachment);
        if(!save){
            throw new RuntimeException("上传文件失败");
        }
        return Result.common(attachment.getId());
    }


    /**
     * 附件删除
     *  删除oos和表中数据
     * @param id id
     * @return {@link Result}<{@link Object}>
     */
    @ApiOperation("文件删除")
    @DeleteMapping("/del/{id}")
    public Result<Object> del(@PathVariable("id") Integer id){
        String fileName = attachmentService.getById(id).getSaveName();
        boolean b = attachmentService.removeById(id);
        if(!b){
            throw new RuntimeException("文件删除失败");
        }
        ossClient.deleteObject(BUCKETNAME,fileName);
        return Result.common(b);
    }


    /**
     * 文件下载，根据附件编号返回url,只适用于此项目
     *
     * @return {@link Result}<{@link Object}>
     */
    @ApiOperation("文件下载")
    @GetMapping("/download/{attachmentId}")
    public Result<Object> download(@PathVariable("attachmentId") Integer id){
        String url = attachmentService.getById(id).getUrl();
        return Result.common(url);
    }


}

